import requests
import re
import traceback
from bs4 import BeautifulSoup

import bs4


def getHTMLText(url, code='utf-8'):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()
        r.encoding = code
        return r.text
    except:
        return "访问失败"


def getStokList(lst, stockUrl):
    html = getHTMLText(stockUrl, 'GB2312')
    soup = BeautifulSoup(html, "html.parser")
    a = soup.find_all('a')
    for i in a:
        try:
            href = i.attrs['href']
            lst.append(re.findall(r"[s][hz]\d{6}", href)[0])
        except:
            continue


def getStockinfo(lst, stockurl, fpth):
    count = 0;
    for stock in lst:
        url = stockurl + stock + ".html"
        html = getHTMLText(url)
        try:
            if html == "":
                continue
            infoDict = {}
            soup = BeautifulSoup(html, "html.parser")
            stockinfo = soup.find('div', attrs={'class': 'stock-bets'})

            name = stockinfo.find_all(attrs={'class': 'bets-name'})[0]
            infoDict.update({'股票名称': name.text.split()[0]})

            keylist = stockinfo.find_all('dt')
            valuelist = stockinfo.find_all('dd')

            for i in range(len(keylist)):
                key = keylist[i].text
                val = valuelist[i].text
                infoDict[key] = val

            with open(fpth, 'a', encoding='utf-8') as f:
                f.write(str(infoDict)+'\r\n')
                count += 1
                print('\r当前速度：{:2f}%'.format(count * 100 / len(lst), end=''))
        except:
            count += 1
            print('\r当前速度：{:2f}%'.format(count * 100 / len(lst), end=''))
            traceback.print_exc()
            continue


def main():
    stok_list_url = 'http://quote.eastmoney.com/stocklist.html'
    stok_info_url = 'https://gupiao.baidu.com/stock/'
    out_file = 'D://BaiduStockInfo.txt'
    slist = []
    getStokList(slist, stok_list_url)
    getStockinfo(slist, stok_info_url, out_file)


if __name__ == '__main__':
    main()
